package com.cxsy.hxl.service.impl;

import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csxy.hxl.JwtUtils;
import com.csxy.hxl.MD5;
import com.csxy.hxl.exception.MyException;
import com.cxsy.hxl.entity.UcenterMember;
import com.cxsy.hxl.entity.vo.LoginVo;
import com.cxsy.hxl.entity.vo.RegisterVo;
import com.cxsy.hxl.mapper.UcenterMapper;
import com.cxsy.hxl.service.UcenterService;
import org.springframework.stereotype.Service;

@Service
public class UcenterServiceImpl extends ServiceImpl<UcenterMapper, UcenterMember> implements UcenterService {
    @Override
    public String login(LoginVo loginVo) {
        String mobile = loginVo.getPhone();
        String password = loginVo.getPassword();

        if (StringUtils.isEmpty(mobile) && StringUtils.isEmpty(password)){
            throw new RuntimeException("手机号和密码不能为空");
        }
        QueryWrapper<UcenterMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        UcenterMember member = baseMapper.selectOne(queryWrapper);
        if (member == null){
            throw new MyException(20001,"手机号不存在");
        }
        if (!MD5.encrypt(password).equals(member.getPassword())){
            throw new MyException(20001,"密码错误");
        }
        if (member.getIsDisabled()){
            throw new MyException(20001,"账号被禁用");
        }
        String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());
        return token;
    }

    @Override
    public void register(RegisterVo registerVo) {
        String nickname = registerVo.getNickname();
        String mobile = registerVo.getMobile();
        String password = registerVo.getPassword();
        String code = registerVo.getCode();

        if (StringUtils.isEmpty(nickname)
            || StringUtils.isEmpty(mobile)
                || StringUtils.isEmpty(password)
                    || StringUtils.isEmpty(code)){
            throw new MyException(20001,"传来的数据有空值，注册失败");
        }
        if (!code.equals("7777")){
            throw new MyException(20001,"验证码错误，注册失败");
        }
        QueryWrapper<UcenterMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",mobile);
        Long count = baseMapper.selectCount(queryWrapper);
        if (count >= 1){
            throw new MyException(20001,"手机号已存在，注册失败");
        }
        UcenterMember member = new UcenterMember();
        member.setMobile(mobile);
        member.setPassword(MD5.encrypt(password));
        member.setNickname(nickname);
        member.setIsDisabled(false);
        member.setAvatar("https://ts4.tc.mm.bing.net/th/id/OIP-C.MqovI15z6O3xqrbcjHUm4gAAAA?rs=1&pid=ImgDetMain&o=7&rm=3");
        baseMapper.insert(member);
    }
}
